<!-- 网站管理  -->
<template>
  <template v-if="!isAddWebsite">
    <ContentWrap :show-border="false">
      <SearchBox
        :queryForm="searchList"
        :showExpland="false"
        :defaultProps="defaultProps"
        @query="handleSearchQuery"
        :show-export="false"
        :show-len="4"
      />
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap :show-border="false">
      <el-row :gutter="10" class="mb6">
        <el-col :span="1.5" class="el-btn">
          <el-button
            type="primary"
            color="#3721FF"
            class="add-website-btn"
            @click="handleAddWebsite"
          >
            <Icon class="mr-2px" icon="ep:plus" />
            新增网站
          </el-button>
          <el-button
            type="primary"
            color="#EFEDFF"
            class="add-website-btn"
            style="color: #3721ff"
            @click="handleBatchVerify"
            :disabled="selections.length == 0"
          >
            批量验证
          </el-button>
          <el-button
            type="primary"
            color="#EFEDFF"
            class="add-website-btn"
            style="color: #3721ff"
            @click="handleBatchExport"
          >
            批量导出
          </el-button>
        </el-col>
        <el-col :span="1.5" style="display: flex; align-items: center">
          <div class="text-[14px]"
            >已选择<span class="text-blue-600 pl-2px pr-2px">{{ selections.length }}</span
            >条</div
          >
        </el-col>
      </el-row>
      <el-table
        v-loading="loading"
        :data="list"
        :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#333' }"
        class="rounded-lg"
        @select="handleSelectionChange"
        @select-all="handleAllSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="网站logo" width="120">
          <template #default="{ row }">
            <div class="flex">
              <ImagePreview :src="row.webLogo" width="50px" height="50px" />
              <!--              <el-image-->
              <!--                fit="cover"-->
              <!--                :src="row.webLogo"-->
              <!--                class="flex-none w-50px h-50px"-->
              <!--                @click="imagePreview(row.webLogo)"-->
              <!--              />-->
            </div>
          </template>
        </el-table-column>
        <el-table-column label="网站名称" prop="webName" />
        <el-table-column align="center" label="域名" prop="domain" />
        <el-table-column
          align="center"
          label="地区"
          prop="area"
          :filters="regionFiltersAdress"
          :filter-method="filterHandler"
        >
          <template #filter-icon>
            <Icon class="ml-2px" icon="ic:baseline-filter-alt" />
          </template>
          <!-- 自定义筛选弹窗内容 -->
          <template #filter="{ column }">
            <div class="custom-filter-panel">
              <!-- 搜索框 -->
              <el-input
                v-model="searchText"
                placeholder="搜索地区"
                clearable
                size="small"
                style="margin-bottom: 10px"
              />

              <!-- 筛选选项列表 -->
              <div style="max-height: 200px; overflow-y: auto">
                <el-checkbox-group v-model="selectedRegions">
                  <el-checkbox
                    v-for="item in filteredOptions(column.filters)"
                    :key="item.value"
                    :label="item.value"
                    style="display: block; margin: 5px 0"
                  >
                    {{ item.text }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="语言"
          prop="language"
          :filters="regionFiltersLanguage"
          :filter-method="filterHandler"
        >
          <template #filter-icon>
            <Icon class="ml-2px" icon="ic:baseline-filter-alt" />
          </template>
        </el-table-column>
        <el-table-column
          width="160"
          align="center"
          label="状态"
          prop="status"
          :filters="regionFiltersStatus"
          :filter-method="filterHandler"
        >
          <template #filter-icon>
            <Icon class="ml-2px" icon="ic:baseline-filter-alt" />
          </template>
          <template #default="{ row }">
            <el-tag :type="webStatus.find((at) => at.value == row.status)?.type">{{
              webStatus.find((at) => at.value == row.status)?.label
            }}</el-tag>
            <span
              class="text-blue-600 text-[12px] pl-2 cursor-pointer"
              @click="goWebsiteAnalysis(row.id)"
              v-if="row.status == 1"
              >去验证 ></span
            >
          </template>
        </el-table-column>
        <el-table-column align="center" label="创建部门" prop="deptName" />
        <el-table-column align="center" label="创建者" prop="nickName" width="180" />
        <el-table-column
          :formatter="dateFormatter"
          align="center"
          label="创建时间"
          prop="createTime"
          width="180"
        />
        <el-table-column
          align="center"
          fixed="right"
          label="操作"
          min-width="200"
          class-name="all-button"
        >
          <template #default="{ row }">
            <el-button link type="primary" color="#3721FF" plain @click="openDetail(row.id)">
              编辑
            </el-button>
            <el-button link type="primary" color="#3721FF" plain @click="openPreview(row)">
              预览
            </el-button>
            <el-button link type="primary" color="#3721FF" plain @click="goCopy(row.id)">
              复制
            </el-button>
            <el-dropdown trigger="click" class="ml-12px">
              <el-button link type="primary" color="#3721FF" plain> 更多 </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="goSetNavigation(row.id,row.domain)">导航设置</el-dropdown-item>
                  <el-dropdown-item @click="handleDelete(row.id)">删除</el-dropdown-item>
                  <el-dropdown-item @click="goWebsiteAnalysis(row.id)">网站解析</el-dropdown-item>
                  <el-dropdown-item @click="handleClearWebsiteData(row.id)"
                    >清空站点数据</el-dropdown-item
                  >
                  <el-dropdown-item @click="handleTopPosition(row)">{{
                    row.isTop == 1 ? '置顶' : '取消置顶'
                  }}</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNo"
        :total="total"
        @pagination="getList"
      />
    </ContentWrap>
  </template>
  <AddWebsite
    ref="addWebsiteRef"
    v-if="isAddWebsite"
    :isAddWebsite="isAddWebsite"
    @close="isAddWebsite = false"
    @refresh="getList"
    :selectedId="selectedId"
  />
  <AddCopy v-if="isAddCopy" :copyId="copyId" @close="isAddCopy = false" @refresh-list="getList" />
  <WebsiteAnalysis
    v-if="isWebsiteAnalysis"
    :isWebsiteAnalysis="isWebsiteAnalysis"
    @close="isWebsiteAnalysis = false"
    :selectedId="selectedId"
    @refresh="getList"
  />
  <!-- 正常删除弹窗 -->
  <ComfirmPops
    ref="deletePopsRef"
    :show-icon="true"
    width="500px"
    :show-dot="false"
    type="idTips"
    title="删除"
    :id="delSelected"
    @confirm="getDeletePops"
  >
    <template #content>
      <p>确定删除吗？</p>
    </template>
  </ComfirmPops>
  <!-- 批量验证 -->
  <ComfirmPops
    ref="batchVerifyRef"
    :show-icon="true"
    width="500px"
    :show-dot="false"
    type="idTips"
    title="批量验证"
    @confirm="getBatchVerifyPops"
  >
   <template #content>
      <p>确定批量验证吗？</p>
    </template>
  </ComfirmPops>
  <!-- 清空站点 -->
  <ComfirmPops
    ref="clearSetDataRef"
    :show-icon="true"
    width="500px"
    :show-dot="false"
    type="idTips"
    title="清空站点库存"
    @confirm="getClearSetDataPops"
  />
  <!-- 置顶 -->
  <ComfirmPops
    ref="topPositionRef"
    :show-icon="true"
    width="500px"
    :show-dot="false"
    type="idTips"
    title="置顶"
    @confirm="getTopPositionPops"
  >
    <template #content>
      <p
        >确定{{ topPositionSelected?.isTop == 1 ? '置顶' : '取消置顶' }}
        <span class="text-[#3721FF]">{{ topPositionSelected?.webName }}</span> 吗？</p
      >
    </template>
  </ComfirmPops>
    <!-- 批量导出 -->
  <ComfirmPops
    ref="batchExportPopsRef"
    :show-icon="true"
    width="500px"
    :show-dot="false"
    type="idTips"
    title="批量导出"
    @confirm="getBatchExportPops"
  >
    <template #content>
      <p>确定{{selections.length==0?'全部':'选中'}}导出吗？</p>
    </template>
  </ComfirmPops>
</template>
<script lang="ts" setup>
import { linkEmits, TabsPaneContext } from 'element-plus'
import { createImageViewer } from '@/components/ImageViewer'
import { dateFormatter } from '@/utils/formatTime'
import AddWebsite from './addWebsite.vue'
import AddCopy from './addCopy.vue'
import WebsiteAnalysis from './websiteAnalysis.vue'
import { defaultProps, handleTree, treeToString } from '@/utils/tree'
import { ProductSpuStatusEnum } from '@/utils/constants'
import { fenToYuan } from '@/utils'
import download from '@/utils/download'
import { WebSiteApi, WebSiteVO } from '@/api/website/website'
import ImagePreview from '@/components/ImagePreview/index.vue'
import { webStatus } from '@/utils'
import type { TradeOrderQueryVO } from '@/api/mall/trade/order'
import * as DeptApi from '@/api/system/dept'
import { getDeptUserTree } from '@/api/roll'
import { ProductApi } from '@/api/product/addProduct'
import { handlegetLanguageList, handleGetGlobeState } from '@/utils/index'

defineOptions({ name: 'ProductSpu' })
const batchExportPopsRef = ref() // 批量导出弹窗
const proDeptList = ref() // 部门列表
const batchVerifyRef = ref() // 批量验证弹窗
const clearSetDataRef = ref() // 情况站点弹窗
const topPositionRef = ref() // 置顶弹窗
const treeData = ref([])
const addWebsiteRef = ref()
const selectedId = ref() // 选中的id
const selections = ref([])
const message = useMessage() // 消息弹窗
const route = useRoute() // 路由
const { t } = useI18n() // 国际化
const { push } = useRouter() // 路由跳转
const deletePopsRef = ref() // 删除弹窗
const loading = ref(false) // 列表的加载中
const exportLoading = ref(false) // 导出的加载中
const total = ref(0) // 列表的总页数
const isAddCopy = ref(false) // 是否复制
const delSelected = ref(0) // 删除的id
const isWebsiteAnalysis = ref(false) // 是否网站解析
const copyId = ref(0) // 复制的ID
const list = ref<WebSiteVO[]>([]) // 列表的数据
const isAddWebsite = ref(false) // 是否新增网站组件
// tabs 数据
const tabsData = ref([
  {
    name: '出售中',
    type: 0,
    count: 0
  },
  {
    name: '仓库中',
    type: 1,
    count: 0
  },
  {
    name: '已售罄',
    type: 2,
    count: 0
  },
  {
    name: '警戒库存',
    type: 3,
    count: 0
  },
  {
    name: '回收站',
    type: 4,
    count: 0
  }
])

const searchList = ref([
  {
    label: '网站名称',
    code: 'webName',
    type: 'input'
  },
  {
    label: '域名',
    code: 'domain',
    type: 'input'
  },
  {
    label: '创建部门',
    code: 'deptId',
    type: 'treeSelect',
    options: proDeptList
  },
  {
    label: '创建者',
    code: 'userId',
    type: 'select',
    options: treeData
  }
])

// 所有可筛选的地区选项
const regionFiltersAdress = ref([])
const regionFiltersLanguage = ref([])
const regionFiltersStatus = ref([])

const initQueryParams = {
  pageNo: 1,
  pageSize: 10,
  tabType: 0,
  name: '',
  categoryId: undefined,
  createTime: undefined
}
//
const topPositionSelected = ref(undefined)
const handleTopPosition = (val) => {
  topPositionSelected.value = val
  topPositionRef.value.show(val.id)
  console.log(val)

  getList()
}
//预览
const openPreview = (row) => {
  window.open('https://'+ row.domain, '_blank')
  // 跳转到预览页面
}
// 去验证
const handleVerify = (id) => {}
let queryParams = ref({
  ...initQueryParams
}) // 查询参数
const queryFormRef = ref() // 搜索的表单Ref

// 搜索关键词
const searchText = ref('')
// 已选中的地区
const selectedRegions = ref([])
const router = useRouter() // 路由
const goSetNavigation = (id,domain) => {
  router.push({ name: 'SetNavigation', query: { id ,domain} })
}
// 选中参数操作
const handleSelectionChange = (val) => {
  selections.value = val.map((item) => item.id)
}
// 清空站点库存
const handleClearWebsiteData = (id: number) => {
  clearSetDataRef.value.show(id)
}
const getClearSetDataPops = (bool, id) => {
  WebSiteApi.clearSiteData(id).then((res) => {
    message.success('清空成功')
    getList()
  })
}
// 置顶
const getTopPositionPops = (bool, id) => {
  WebSiteApi.toggleTop(id).then((res) => {
    message.success('置顶成功')
    getList()
  })
}
// 全选
const handleAllSelectionChange = (val) => {
  selections.value = val.map((item) => item.id)
}
// 批量验证
const handleBatchVerify = () => {
  batchVerifyRef.value.show(selections.value.join(','))
}
// 批量导出
const handleBatchExport = () => {
  batchExportPopsRef.value.show(selections.value.join(','))
}
const getBatchExportPops = (bool, ids) => {
  let params = {
    ids: ids?ids.split(','):'',
  }
  WebSiteApi.exportDnsExcel(params).then((res) => {
    // download.excel(res, '网站列表记录.xlsx')
    message.success('下载成功')
  })
}
const getBatchVerifyPops = (bool, ids) => {
  let idsArr = ids && ids.length > 0 ? ids.split(',') : []
  WebSiteApi.batchDomainVerification({ websiteIds: idsArr }).then((res) => {
    message.success(res.message)
    getList()
  })
}

//人员
const handlegetDeptUserTree = async () => {
  // const res = await getDeptUserTree()
  const res = await ProductApi.listAllSimple()
  treeData.value = res.map((item) => ({
    label: item.nickname,
    value: item.id
  }))
}
const handleSearchQuery = (val) => {
  /***
   * 搜索框查询条件，目前考虑在查询时 queryParams = {...val,pageNo:1,pageSize:10}
   * */
  queryParams.value = { ...val, pageNo: 1, pageSize: 10 }
  getList()
}
// 获取部门列表
const getDeptList = async () => {
  try {
    proDeptList.value = handleTree(await DeptApi.getSimpleDeptList())
  } catch (error) {
    console.error('获取部门列表失败:', error)
  }
}
// 复制
const goCopy = (id: number) => {
  isAddCopy.value = true
  copyId.value = id
}
// 网站分析
const goWebsiteAnalysis = (id: number) => {
  isWebsiteAnalysis.value = true
  selectedId.value = id
}
// 根据搜索词过滤选项
const filteredOptions = (filters) => {
  return filters.filter((item) => item.text.includes(searchText.value))
}
const handleAddWebsite = () => {
  selectedId.value = null
  isAddWebsite.value = true
  // 清空所有数据子组件AddWebsite里面的数据
  addWebsiteRef.value?.resetForm()
}
// 筛选逻辑
const filterHandler = (value: string, row: any, column: TableColumnCtx<any>) => {
  const property = column['property']
  return row[property] == value
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await WebSiteApi.getWebSitePage(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 切换 Tab */
const handleTabClick = (tab: TabsPaneContext) => {
  queryParams.value.tabType = tab.paneName as number
  getList()
}

/** 获得每个 Tab 的数量 */
const getTabsCount = async () => {
  const res = await ProductSpuApi.getTabsCount()
  for (let objName in res) {
    tabsData.value[Number(objName)].count = res[objName]
  }
}

/** 添加到仓库 / 回收站的状态 */
const handleStatus02Change = async (row: any, newStatus: number) => {
  try {
    // 二次确认
    const text = newStatus === ProductSpuStatusEnum.RECYCLE.status ? '加入到回收站' : '恢复到仓库'
    await message.confirm(`确认要"${row.name}"${text}吗？`)
    // 发起修改
    await ProductSpuApi.updateStatus({ id: row.id, status: newStatus })
    message.success(text + '成功')
    // 刷新 tabs 数据
    await getTabsCount()
    // 刷新列表
    await getList()
  } catch {}
}

/** 更新上架/下架状态 */
const handleStatusChange = async (row: any) => {
  try {
    // 二次确认
    const text = row.status ? '上架' : '下架'
    await message.confirm(`确认要${text}"${row.name}"吗？`)
    // 发起修改
    await ProductSpuApi.updateStatus({ id: row.id, status: row.status })
    message.success(text + '成功')
    // 刷新 tabs 数据
    await getTabsCount()
    // 刷新列表
    await getList()
  } catch {
    // 异常时，需要重置回之前的值
    row.status =
      row.status === ProductSpuStatusEnum.DISABLE.status
        ? ProductSpuStatusEnum.ENABLE.status
        : ProductSpuStatusEnum.DISABLE.status
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  deletePopsRef.value.show(id)
  delSelected.value = id
}
const getDeletePops = async (bool, id) => {
  try {
    // 删除的二次确认
    // await message.delConfirm()
    // // 发起删除
    // await ProductSpuApi.deleteSpu(id)
    WebSiteApi.deleteWebSite(id).then(async () => {
      message.success(t('common.delSuccess'))
      await getList()
    })
    // 刷新tabs数据
    await getTabsCount()
    // 刷新列表
  } catch {}
}
/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 新增或修改 */
const openForm = (id?: number) => {
  // 修改
  if (typeof id === 'number') {
    push({ name: 'ProductSpuEdit', params: { id } })
    return
  }
  // 新增
  push({ name: 'ProductSpuAdd' })
}

/** 查看商品详情 */
const openDetail = (id: number) => {
  // push({ name: 'ProductSpuDetail', params: { id } })
  isAddWebsite.value = true
  selectedId.value = id
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ProductSpuApi.exportSpu(queryParams.value)
    download.excel(data, '商品列表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取分类的节点的完整结构 */
const categoryList = ref() // 分类树
const formatCategoryName = (categoryId: number) => {
  return treeToString(categoryList.value, categoryId)
}

/** 激活时 */
onActivated(() => {
  getList()
})

/** 初始化 **/
onMounted(async () => {
  regionFiltersLanguage.value = await handlegetLanguageList() //语言
  let adress = await handleGetGlobeState()
  regionFiltersAdress.value = adress.map((item) => {
    return {
      ...item,
      text: item.label,
      value: item.label
    }
  })
  regionFiltersStatus.value = webStatus.map((item) => {
    return {
      ...item,
      text: item.label,
      value: item.value
    }
  })
  await getList()
  getDeptList()
  handlegetDeptUserTree()
})
</script>
<style scoped>
@import '@/styles/website.scss';
</style>
